package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.UploadPicService;
import com.tanhua.common.vo.UploadPicResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class UserInfoService {
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private FaceEngineService faceEngineService;
    @Autowired
    private UploadPicService uploadPicService;

    public Boolean saveUserInfo(Map<String, String> data, String token) {
        User user = userService.queryUserByToken(token);
        if (null == user) {
            return false;
        }
        UserInfo userInfo = new UserInfo();
        String gender = data.get("gender");
        String nickname = data.get("nickname");
        String birthday = data.get("birthday");
        String city = data.get("city");
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equals(gender, "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(nickname);
        userInfo.setBirthday(birthday);
        userInfo.setCity(city);
        return userInfoMapper.insert(userInfo) == 1;
    }

    public boolean saveUserImage(MultipartFile multipartFile, String token) {
        User user = userService.queryUserByToken(token);
        if (null == user) {
            return false;
        }
        boolean isPerson = false;
        try {
            isPerson = faceEngineService.checkIsPortrait(multipartFile.getBytes());
            if (!isPerson) {
                return false;
            }
        } catch (IOException e) {
            return false;
        }
        UploadPicResult uploadPicResult = uploadPicService.uploadPic(multipartFile);
        String url = uploadPicResult.getName();
        if (StringUtils.isEmpty(url)) {
            return false;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(url);
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getUserId, user.getId());
        return userInfoMapper.update(userInfo, wrapper) == 1;
    }
}
